using System;
using System.Collections.Generic;
using System.Text;

using System.Xml;

using GSN.Config;

namespace GSN.Rules
{
    class AllowedSendersRule : IMsgRule
    {
        private string[] allowedSenders = null;

        #region IRule Members

        public string getName()
        {
            return "Allowed Senders Rule";
        }

        public string getDescription()
        {
            return "Allows you to define a list of allowed senders. GSN will notify you ONLY about e-mails from those senders.";
        }

        public bool showConfigDialog(IConfigurator configurator)
        {
            configurator.setItemStringArray(allowedSenders, "Senders");

            if (configurator.show())
            {
                allowedSenders = configurator.getItemStringArray("Senders");

                return true;
            }

            return false;
        }

        public void load(System.Xml.XmlNode node)
        {
            XmlNodeList sendersList = node.SelectNodes("Sender");

            List<string> s = new List<string>(sendersList.Count);

            foreach (XmlNode sender in sendersList)
            {
                s.Add(sender.InnerText);    
            }

            allowedSenders = s.ToArray();
            s = null;
        }

        public void save(System.Xml.XmlWriter w)
        {
            w.WriteStartElement("Rule");

            w.WriteElementString("Type", this.GetType().Name);

            foreach (string sender in allowedSenders)
            {
                w.WriteElementString("Sender", sender);
            }

            w.WriteEndElement();
        }

        public bool apply(GSN.Mail.Messages.Message msg)
        {
            bool result = false;

            foreach (string s in allowedSenders)
            {
                if (msg.from.ToLower().Contains(s.ToLower()))
                {
                    result = true;
                    break;
                }
            }

            return result;
        }

        public string getConfiguratorTypeName()
        {
            return "GSNConf.Rules.AllowedSendersRuleConfigurator";
        }

        #endregion
    }
}
